<template>
  <div class="login-account">
    <el-form
      label-width="80px"
      label-position="right"
      :rules="rules"
      :model="account"
      ref="formRef"
    >
      <el-form-item label="email" prop="email">
        <el-input v-model="account.email" />
      </el-form-item>
      <el-form-item label="password" prop="hash">
        <!-- <el-col :span="21"> -->
        <el-input v-model="account.hash" show-password />
        <!-- </el-col> -->
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, ref } from 'vue'
import { useStore } from 'vuex'
import { ElForm } from 'element-plus'
import localCache from '@/utils/cache'

import { rules } from '../config/account-config'

export default defineComponent({
  setup() {
    const store = useStore()

    const account = reactive({
      email: localCache.getCache('email') ?? '',
      hash: localCache.getCache('password') ?? ''
    })

    const formRef = ref<InstanceType<typeof ElForm>>()

    const loginAction = (isKeepPassword: boolean) => {
      formRef.value?.validate((valid) => {
        if (valid) {
          // 判断是否需要记住密码
          if (isKeepPassword) {
            // 本地缓存
            localCache.setCache('email', account.email)
            localCache.setCache('password', account.hash)
          } else {
            localCache.deleteCache('email')
            localCache.deleteCache('password')
          }

          // 开始进行登录验证,异步请求通过vuex的actions提交给mutation
          store.dispatch('login/accountLoginAction', { ...account })
        }
      })
    }

    return {
      account,
      rules,
      loginAction,
      formRef
    }
  }
})
</script>

<style scoped></style>
